package spade;

public class PeriodicBehaviour extends Behaviour
{
	long	period;
	long	nextActivation;
	public PeriodicBehaviour(long period, Long timestart)
	{
		super();
		this.period = period;
		if (timestart == null)
		{
			this.nextActivation = System.currentTimeMillis();
		}
		else
		{
			this.nextActivation = timestart;
		}
	}
	public long getPeriod()
	{
		return period;
	}
	public void setPeriod(long period)
	{
		this.period = period;
	}
	public int process()
	{
		if (System.currentTimeMillis() >= this.nextActivation)
		{
			this.exitcode = this.onTick();
			while (this.nextActivation <= System.currentTimeMillis())
			{
				this.nextActivation += this.period;
			}
		}
		else
		{
			long t = this.nextActivation - System.currentTimeMillis();
			if (t > 0)
			{
				try
				{
					Thread.sleep(t);
				}
				catch (InterruptedException e)
				{
					e.printStackTrace();
				}
			}
		}
		return 0;
	}
	public int onTick()
	{
		throw new RuntimeException("Not implemented");
	}
}
